package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.*;

/**
 * CompletableFuture
 * <p>不推荐使用默认的ForkJoinPool(有io操作会造成线程饥饿)
 */
public class _12_ThreadPool_CompletableFuture {
    /*
     * 泡茶流程：
     * 洗水壶 --> 烧水  --------------> 泡茶
     * 洗茶壶 --> 洗茶杯 --> 拿茶叶-------↑
     */

    public static void main(String[] args) {
        final ThreadPoolExecutor pool
                = new ThreadPoolExecutor(2,
                2,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20),
                new ThreadPoolExecutor.CallerRunsPolicy());

        CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {
            System.out.println("T1:洗水壶...");
            sleep(1, TimeUnit.SECONDS);
            System.out.println("T1:烧开水...");
            sleep(15, TimeUnit.SECONDS);
        }, pool);

        CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("T2:洗茶壶...");
            sleep(1, TimeUnit.SECONDS);
            System.out.println("T2:洗茶杯...");
            sleep(2, TimeUnit.SECONDS);
            System.out.println("T2:拿茶叶...");
            sleep(1, TimeUnit.SECONDS);
            return "龙井";
        }, pool);

        CompletableFuture<String> f3 = f1.thenCombineAsync(f2, (a, tf) -> {
            System.out.println("T1:拿到茶叶:" + tf);
            System.out.println("T1:泡茶...");
            return "上茶: " + tf;
        }, pool);
        System.out.println(f3.join());
        pool.shutdown();

        CompletableFuture<Integer>
                f0 = CompletableFuture
                .supplyAsync(() -> (7 / 0))
                .thenApply(r -> r * 10)
                .exceptionally(e -> -1)
                .whenComplete((a, b) -> System.out.println(a + ", " + b))
                .handle((a, b) -> 3)
                ;
        System.out.println(f0.join());
    }

    private static void sleep(int t, TimeUnit u) {
        try {
            u.sleep(t);
        } catch (InterruptedException e) {
        }
    }
}
